package bb.lanxing.fragment.team;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.LitePal;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import bb.lanxing.R;
import bb.lanxing.activity.team.TeamDetailActivity;
import bb.lanxing.adapter.team.TeamListAdapter;
import bb.lanxing.fragment.base.BaseFragment;
import bb.lanxing.model.database.Event;
import bb.lanxing.network.BiCiCallback;
import bb.lanxing.network.MyHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class TeamListFragment extends BaseFragment {
    public static final int LIST_TYPE_NEARBY = 0;
    public static final int LIST_TYPE_MY = 1;
    public static final int LIMIT = 10;

    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView mRecyclerView;
    private TeamListAdapter mAdapter = null;
    private List<Event> mEventList = new ArrayList<>();
    private int type;
    private Handler mHandler = new Handler();

    private int pageMax = 1;
    private int page = 1;
    private ProgressDialog progressDialog;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_team_list, container, false);

        progressDialog = new ProgressDialog(getContext());
        swipeRefreshLayout = view.findViewById(R.id.swipe_refresh_layout);
        swipeRefreshLayout.setOnRefreshListener(() -> loadData(true));
        mRecyclerView = view.findViewById(R.id.recyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (!recyclerView.canScrollVertically(1)) {
                    loadData(false);
                }
            }
        });
        mAdapter = new TeamListAdapter();
        mAdapter.setOnItemClickListener(position -> {
            Event event = mEventList.get(position);
            if (event != null) {
                Intent intent = new Intent(getActivity(), TeamDetailActivity.class);
                intent.putExtra("event_id", event.getEventId());
                getActivity().startActivityForResult(intent, 76);
            }
        });
        mRecyclerView.setAdapter(mAdapter);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        loadData(true);
    }

    public void loadData(final boolean bPullDown) {
        if (bPullDown) {
            page = 1;
        } else {
            page++;
            if (page > pageMax) {
                return;
            }
            progressDialog.show();
        }
        BiCiCallback biCiCallback = new BiCiCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                super.onFailure(request, e);
                if (swipeRefreshLayout != null) {
                    swipeRefreshLayout.setRefreshing(false);
                }
                progressDialog.dismiss();
            }

            @Override
            public void onResponse(Response response) {
                try {
                    super.onResponse(response);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } finally {
                    if (swipeRefreshLayout != null) {
                        swipeRefreshLayout.setRefreshing(false);
                    }
                    progressDialog.dismiss();
                }
            }

            @Override
            public void onResponseString(@NonNull String string) {
                ArrayList<Event> arrayList = new ArrayList<>();
                try {
                    int totalListNumber = new JSONObject(string).optInt("total");
                    pageMax = totalListNumber / 10;
                    if (totalListNumber % 10 > 0) {
                        pageMax++;
                    }
                    JSONArray jSONArray = new JSONObject(string).getJSONArray("rows");
                    for (int i = 0; i < jSONArray.length(); i++) {
                        Event createByJson = Event.createByJson(jSONArray.getJSONObject(i));
                        long eventId = createByJson.getEventId();
                        Event localEvent = LitePal.where("eventId=?", String.valueOf(eventId)).findFirst(Event.class);
                        if (localEvent != null && localEvent.getEventId() == eventId) {
                            createByJson.setId(localEvent.getId());
                        }
                        createByJson.save();
                        arrayList.add(createByJson);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                updateDatas(arrayList, bPullDown);
            }
        };
        if (type == LIST_TYPE_NEARBY) {
            MyHttpClient.requestNearbyActivities(biCiCallback, page, LIMIT);
        } else if (type == LIST_TYPE_MY) {
            MyHttpClient.requestMyActivities(biCiCallback, page, LIMIT, 2);
        }
    }

    private synchronized void updateDatas(final List<Event> eventList, final boolean needClean) {
        if (eventList == null) {
            return;
        }
        mHandler.post(() -> {
            if (mAdapter != null) {
                if (needClean) {
                    mEventList.clear();
                }
                mEventList.addAll(eventList);
                mAdapter.updateData(mEventList);
            }
        });
    }

    public void setType(int type) {
        this.type = type;
    }
}